#!/usr/bin/env bash

# We need globstar on
shopt globstar | grep -q 'off$' && { RESET_GLOBSTAR=1; shopt -s globstar ; }

for i in ./**/**; do { \
    # skip directories and binary files
    grep -qI -d skip '.' "$i" && ( \
        # change CRLF to LF (dos2unix)
        tr -d '\15\32' < "$i" | \
        # change tabs to 4 spaces
        expand -t 4 | \
        # remove space after ( and before )
        # sed -e 's/( /(/g' -e 's/ )/)/g' | \
        # remove trailing spaces
        sed 's/[[:space:]]*$//g' > o; \
        # ensure nl at end of file
        [[ "$(tail -c1 o;echo x)" != $'\nx' ]] && echo '' >> o; \
        # replace target with tmp file
        cat o > "$i" && rm o \
    ) ; \
} ; done

# Turn off globstar if we turned it on
[[ $RESET_GLOBSTAR == 1 ]] && shopt -u globstar

